package com.zhanghp.class030;

/**
 * <p>用异或运算交换两数的值</p>
 * <p>要求2块独立的空间</p>
 *
 * @author zhanghp
 * @since 2024/4/3 16:32
 */
public class Code01_SwapExclusiveOr {

    public static void main(String[] args) {
        // 1
        // a ^ b虽然为0，但 0^b本身 = b
        // 而a= b,所以a = 0 ^ b = b
        // 所以两数交换完都是1
        int a = 1;
        int b = 1;
        a = a ^ b;
        b = a ^ b;
        a = a ^ b;
        System.out.println(a);
        System.out.println(b);


        System.out.println("==============");
        // 2
        a = 2;
        b = 3;
        a = a ^ b;
        b = a ^ b;
        a = a ^ b;
        System.out.println(a);
        System.out.println(b);

        System.out.println("==============");
        // 3
        int[] arr = {3, 5};
        swap(arr, 0, 1);
        System.out.println(arr[0]);
        System.out.println(arr[1]);

        // ==========a ^ a = 0=============
        System.out.println("============");
        int[] arr2 = {2, 3};
        // 交换自己，结果为0
        swap(arr2, 0, 0);
        System.out.println(arr2[0]);
        System.out.println(arr2[1]);

    }

    public static void swap(int[] arr, int a, int b) {
        if (a == b) {
            return;
        }
        arr[a] = arr[a] ^ arr[b];
        arr[b] = arr[a] ^ arr[b];
        arr[a] = arr[a] ^ arr[b];
    }

}
